package org.abettor.pushbox.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import org.abettor.android.ads.YoumiManager;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.db.PushBoxDbHelper;
import org.abettor.pushbox.map.AsyncGenerateMapThumbImage;
import org.abettor.pushbox.map.AsyncGenerateMapThumbImage.ImageCallback;
import org.abettor.pushbox.model.PushBoxMapBean;
import org.abettor.pushbox.util.Resource;
import org.abettor.pushbox.R;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.SpannedString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 经典地图的list activity
 * 
 * @author jzh
 */
public class ClassicMapActivity extends ListActivity {
	private final float WIDTH = 70, HEIGHT = 70;
	private final int SHOW_AD = 13579;
	private SQLiteDatabase base;
	private PushBoxDbHelper dbHelper;
	private Cursor cursor;// 查询数据库的游标
	private YoumiManager youmi = new YoumiManager(this);
	private Handler youmiHandle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SHOW_AD) {
				// 按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if (val < 30) {
					youmi.showYoumi(YoumiManager.Position.top, Color.WHITE,
							Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}
	};
	private Thread youmiDelayThread = new Thread() {
		@Override
		public void run() {
			try {
				Thread.sleep(200);
				Message msg = new Message();
				msg.what = SHOW_AD;
				youmiHandle.sendMessage(msg);
			} catch (InterruptedException e) {
				Log.d(this.getClass().getName(), "", e);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.classic_map_activity);
		dbHelper = new PushBoxDbHelper(this);
		base = dbHelper.getWritableDatabase();// 获得数据库的链接
		cursor = this.getCursor();
		MapListAdapter adapter = new MapListAdapter(this, cursor);
		this.setListAdapter(adapter);
		startManagingCursor(cursor);
		youmiDelayThread.start();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		TextView tv = (TextView) v.findViewById(R.id.status);
		CharSequence seq = tv.getText();
		SpannedString builder = (SpannedString) seq;
		Integer[] it = builder.getSpans(0, builder.length(), Integer.class);
		Intent in = new Intent();
		if (it[0] == 0){//未解决直接返回
			return;
		}else if(it[0]==1){// 已解决
			in.setClass(this, ClassicShowResultActivity.class);
		}else{
			in.setClass(this, ClassicPushBoxActivity.class);
		}
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		in.putExtras(extras);
		startActivity(in);
	}

	private Bitmap readBitmap(File file) {
		FileInputStream is;
		try {
			is = new FileInputStream(file);
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			is.close();
			return bitmap;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private void setImageView(final ImageView thumbImage, final int missionId) {
		// 先判断文件是否存在，存在的话同步操作，否则异步操作
		String filepath = Config.getClassicBasePath() + File.separator
				+ missionId + ".thumb";
		File file = new File(filepath);
		Bitmap bmp = null;
		if (file.exists()) {// 读取存在的文件
			bmp = readBitmap(file);
			if (bmp != null) {
				thumbImage.setImageBitmap(bmp);
				return;
			}
		}
		// 文件不存在，那就异步吧
		ImageCallback callback = new ImageCallback() {
			@Override
			public void processImage(Bitmap bit) {
				thumbImage.setImageBitmap(bit);
			}
		};
		AsyncGenerateMapThumbImage as = new AsyncGenerateMapThumbImage(WIDTH,
				HEIGHT, callback, this) {
			@Override
			public String getThumbNailPath() {
				return Config.getClassicBasePath() + File.separator + missionId
						+ ".thumb";
			}

			@Override
			public String getMapFilePath() {
				return null;
			}

			@Override
			protected byte[] readFile() throws IOException {
				InputStream bin = getResources().openRawResource(
						Resource.getMapResourceByMission(missionId));
				ByteArrayOutputStream bo = new ByteArrayOutputStream();
				int v = 0;
				while ((v = bin.read()) != -1) {
					bo.write(v);
				}
				byte[] buf = bo.toByteArray();
				bin.close();
				bo.close();
				return buf;
			}
		};
		as.start();
	}

	// 获得游标
	private Cursor getCursor() {
		Cursor c = base.query(PushBoxDbHelper.PUSH_BOX_TABLE_NAME,
				new String[] { PushBoxDbHelper.PUSH_BOX_ID,
						PushBoxDbHelper.PUSH_BOX_SOLVED,
						PushBoxDbHelper.PUSH_BOX_MAP_FILENAME,
						PushBoxDbHelper.PUSH_BOX_RESOLVE_TIME,
						PushBoxDbHelper.PUSH_BOX_CREATE_TIME,
						PushBoxDbHelper.PUSH_BOX_MISSION_ID },
				PushBoxDbHelper.PUSH_BOX_TYPE + "="
						+ PushBoxMapBean.CLASSIC_TYPE, null, null, null,
				PushBoxDbHelper.PUSH_BOX_ID);
		return c;
	}

	// 生成列表的adapter
	private class MapListAdapter extends CursorAdapter {
		public MapListAdapter(Context context, Cursor c) {
			super(context, c);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewGroup theparent = (ViewGroup) view;
			setView(theparent, cursor);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = ClassicMapActivity.this
					.getLayoutInflater();
			ViewGroup theparent = (ViewGroup) inflater.inflate(
					R.layout.classic_map_list_item, parent, false);
			return theparent;
		}

		// 列表中设置属性
		private void setView(ViewGroup group, Cursor cursor) {
			TextView missionName = (TextView) group
					.findViewById(R.id.missionname);
			ImageView image = (ImageView) group.findViewById(R.id.locker);
			TextView status = (TextView) group.findViewById(R.id.status);
			status.setText("");
			TextView resovedTime = (TextView) group
					.findViewById(R.id.resovedTime);
			resovedTime.setText("");
			int index = cursor
					.getColumnIndex(PushBoxDbHelper.PUSH_BOX_MISSION_ID);
			int missionId = cursor.getInt(index);
			missionName.setText(ClassicMapActivity.this
					.getText(R.string.mission) + String.valueOf(missionId));
			index = cursor.getColumnIndex(PushBoxDbHelper.PUSH_BOX_SOLVED);
			int has_sovled = cursor.getInt(index);
			image.setVisibility(View.GONE);
			//向上面append值
			SpannableStringBuilder builder = new SpannableStringBuilder();
			CharSequence tmp = null;
			if(has_sovled==1){
				tmp = ClassicMapActivity.this.getText(R.string.finish);
				builder.append(tmp);
				builder.setSpan(has_sovled, 0, tmp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				status.setText(builder);
				
				index = cursor.getColumnIndex(PushBoxDbHelper.PUSH_BOX_RESOLVE_TIME);
				String createTimeStr = cursor.getString(index);
				resovedTime.setText(createTimeStr);
			}else{
				tmp = ClassicMapActivity.this.getText(R.string.unfinish);
				builder.append(tmp);
				builder.setSpan(has_sovled, 0, tmp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				status.setText(builder);
				
				if(has_sovled!=2){
					image.setVisibility(View.VISIBLE);
				}
			}
			ImageView thumbImage = (ImageView) group
					.findViewById(R.id.thumbImage);
			// 回掉显示图片的操作
			setImageView(thumbImage, missionId);
		}
	}
}
